//
//  main.c
//  demo1self
//
//  Created by Song on 2018/3/6.
//  Copyright © 2018年 Song. All rights reserved.
//

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

struct grade {
    int data;
    struct grade *next;
};

typedef struct grade node;

// 创建链表
struct grade *creatt() {
    
    node *head, *tail, *pnew;
    int score;
    
    head = (node *)malloc(sizeof(node)); // 创建头结点
    if (head == NULL) {
        printf("链表创建失败");
        return NULL;
    }
    
    head->next = NULL;
    tail = head;
    
    printf("输入学生成绩：");
    while (1) {
        scanf("%d",&score);
        if (score < 0) {
            break;
        }
        pnew = (node *)malloc(sizeof(node));
        if (pnew == NULL) {
            printf("pnew - null");
            return 0;
        }
        
        pnew->data = score;
        pnew->next = NULL;
        
        tail->next = pnew;
        tail = pnew;
    }
    return head;
}

// 输出链表
void printLink(node *head) {
    
    node *p;
    
    for (p = head->next; p != NULL ; p = p->next) {
        printf("%d ",p->data);
    }
    printf("\n");
}

// 销毁链表
void pfree(node *head) {
    node *p = head, *q;
    while (p->next != NULL) {
        q = p->next;
        p->next = q->next;
        free(q);
    }
    free(p);
}

// 插入链表
void insert(node *head,node *pnew,int i) {
    node *p = head;
    for (int j = 0; j < i && p !=NULL; j++) {
        p = p->next;
    }
    if (p == NULL) {
        printf("插入的节点不存在");
        return;
    }
    
    pnew->next = p->next;
    p->next = pnew;
}

// 删除链表
void pdelete(node *head, int i) {
    node *p = head, *q;
    for (int j = 1; j < i && p->next !=NULL; j++) {
        p = p->next;
    }
    if (p->next == NULL) {
        printf("要删除的节点不存在");
        return;
    }

    q = p->next;
    p->next = q->next;
    free(q);
}

// main
int main(int argc, const char * argv[]) {
    
    node *head, *pnew;
    
    head = creatt();
    if (head == NULL) {
        printf("head - null");
        return 0;
    }
    printf("输出所创建的链表：");
    printLink(head);
    
    pnew = (node *)malloc(sizeof(node));
    if (pnew == NULL) {
        printf("main - pnew - null");
        return 0;
    }
    pnew->data = 88;
    insert(head, pnew, 4); // 第三个节点后插入
    printLink(head);
    
    pdelete(head, 3); // 删除第三个节点
    printLink(head);
    
    pfree(head);
    return 0;
}
